<?php

namespace App\Repositories\Admin;

use App\BaseRepository;
use App\Model\WineProductExpertJudge;
use App\User;
use Illuminate\Support\Facades\DB;

class WineProductJudgeRepository extends BaseRepository
{
    //模型名称
    protected $modelName = "App\Model\WineProductJudge";

    protected $appendCreatorAndUpdater = true;

    protected $appendUserId = true;

    protected function commonRules()
    {
        return [
            'product_id' => 'required',
            'letDrink_judge' => 'required',
            'judge_arr' => 'sometimes|max:10',
        ];
    }

    protected function commonValidate()
    {
        if(!$this->requestValidate($this->commonRules(),$this->commonMessages())) {
            return false;
        }
        if ($this->request->exists('judge_arr')) {
            $rows = $this->request->input('judge_arr');
            if(count($rows) >0 ) {
                foreach ($rows as $row) {
                    if (!isset($row['expert_user_id']) || !isset($row['content'])) {
                        $this->error = 'judge_arr 参数错误';
                        return false;
                    }
                }
            }

        }
        return true;
    }

    protected function processStoreValidate()
    {
        $c = $this->query()->where('product_id','=',$this->request->input('product_id'))->count();
        if($c > 0) {
            $this->error = '记录已存在，请勿重复添加！';
            return false;
        }
        return true;
    }

    private function saveJudges($model)
    {
        if ($this->request->has('judge_arr')) {
            $rows = $this->request->input('judge_arr',[]);

            DB::table('wine_product_expert_judge')->where('judge_id','=',$model->id)->delete();

            foreach ($rows as $row) {
                if (isset( $row['expert_user_id']) && isset($row['content'])) {
                    $m = new WineProductExpertJudge();
                    $m->product_id = $model->product_id;
                    $m->expert_user_id = $row['expert_user_id'];
                    $m->content = $row['content'];
                    if (isset($row['short_review'])&&$row['short_review']) {
                        $m->short_review = $row['short_review'];
                    }
                    if (isset($row['userType'])&&$row['userType']){
                        $m->userType = $row['userType'];
                    }else{
                        $u = User::find($row['expert_user_id']);
                        $m->userType = $u?$u->userType:'expert';
                    }
                    $m->judge_id = $model->id;
                    $m->save();
                }

            }
            return true;
        }
        return false;
    }

    protected function commonSave($model)
    {
        $this->saveJudges($model);
    }


}